<?php
/**
 * 卡片业务层
 * User: Acer
 * Date: 2022/7/8
 * Time: 22:44
 */
namespace app\card\service;

use  app\card\models\CardModel;
use app\card\models\CardProModel;
use app\card\models\CardTypeModel;
use app\move\models\CardUserModel;
use app\move\models\FamilyCardModel;
use app\move\models\IdentityCardModel;
use app\move\service\CardUserService;
use think\Log;

class CardService {

    // 添加卡片
    public function s_add_card($data){
        // 卡片名称不能重复
        $is_cardInfo= (new CardModel())->where(['name'=>$data['name']])->find();
        if($is_cardInfo) json_err( -203,['卡片名称，']);

        $installData = [
            'name'  => $data['name'],
            'ct_id' =>  $data['ct_id'],
            'company'   =>  isset($data['company']) ? $data['company'] : 1,
            'valid_number'   =>  isset($data['valid_number']) ? $data['valid_number'] : 1,
            'money'   =>  isset($data['money']) ? $data['money'] : 0.00,
            'is_charge'   =>  isset($data['is_charge']) ? $data['is_charge'] : 0,
            'state'   =>  isset($data['state']) ? $data['state'] : 0,
            'eid'   =>  isset($data['eid']) ? $data['eid'] :'',
            'prefix'    =>  isset($data['prefix']) ? $data['prefix'] :8,
            'suffix'    =>  isset($data['suffix']) ? $data['suffix'] :6,
            'middle'    =>  isset($data['middle']) ? $data['suffix'] :8,
        ];
        // 查看是否存在相同配置
        $set = $this->getCardCodeNumber($installData['prefix'],$installData['suffix'],$installData['middle']);
        if($set) json_err( -203,['卡片产品编号设置，']);
        $res = (new CardModel())->insert($installData);
        return $res;
    }


    // 获取卡片列表
    public function s_card_list($page,$paginate=10,$like){
        $CardModel = new CardModel();
        $CardModel->alias("c");
        // 卡片种类名称
        if(isset($like['name'])){
            $CardModel->whereLike('c.name','%'.$like['name'].'%');
        }
        if(isset($like['category']) && $like['category']) {
            $CardModel->join("card_type ct", "ct.id=c.ct_id");
            $CardModel->where('ct.category', $like['category']);
        }
        $list = $CardModel->paginate((int)$paginate,false,['page'=>$page])->each(function($item, $key){
            // 获取卡片类型
            $item['type_crder_name'] = (new CardTypeModel())->where(['id'=>$item['ct_id']])->value('card_name');
            // 权益信息,第二版补充

            return $item;
        });
        return obj_to_arr($list);
    }
    // 获取卡片信息
    public function getCardInfo($cid){
        return (new CardModel())->where('cid',$cid)->find();
    }

    /**
     * 组装卡片产品code的唯一性
     * joker
     * @param $prefix   卡片产品编码前缀
     * @param $middle   卡片产品编码前缀
     * @param $suffix   卡片产品编码前缀
     * @param $cid      不包含卡片id
     */
    public function getCardCodeNumber($prefix=null,$middle=null,$suffix=null,$cid= null){
        $CardModel = new CardModel();
        if(!empty($cid)){
            $CardModel->where('cid','<>',$cid);
        }
        if(!empty($prefix) && !empty($suffix)&& !empty($middle) ){
            $CardModel->where([
                'prefix'    =>  $prefix,
                'suffix'    =>  $suffix,
                'middle'    =>  $middle
            ]);
        }
       return $CardModel->find();
    }

    // 修改卡片信息
    public function s_modify_card($data){
        // 卡片是否存在
        $cardInfo= $this->getCardInfo($data['cid']);
        if(!$cardInfo)json_err( -204,['卡片信息，']);
        // 卡片名称不能重复
        $is_cardInfo= (new CardModel())->where('name',$data['name'])->where('cid','<>',$data['cid'])->find();
        if($is_cardInfo) json_err( -203,['卡片名称，']);

        $installData = [
            'name'  => $data['name'],
            'ct_id' =>  $data['ct_id'],
            'company'   =>  isset($data['company']) ? $data['company'] : 1,
            'valid_number'   =>  isset($data['valid_number']) ? $data['valid_number'] : 1,
            'money'   =>  isset($data['money']) ? $data['money'] : 0.00,
            'is_charge'   =>  isset($data['is_charge']) ? $data['is_charge'] : 0,
            'state'   =>  isset($data['state']) ? $data['state'] : 0,
            'eid'   =>  isset($data['eid']) ? $data['eid'] :'',
            'prefix'    =>  isset($data['prefix']) ? $data['prefix'] :8,
            'suffix'    =>  isset($data['suffix']) ? $data['suffix'] :6,
            'middle'    =>  isset($data['middle']) ? $data['suffix'] :8,
        ];
        // 卡片编号配置不能重复
        $set = $this->getCardCodeNumber($installData['prefix'],$installData['suffix'],$installData['middle'],$data['cid']);
        if($set) json_err( -203,['卡片产品编号设置，']);

        $res = (new CardModel())->save($installData,[
          'cid'=>$data['cid']
        ]);
        return $res;
    }
    //修改状态
    public function s_state_card($data){
        if(isset($data['cid'])){
            // 获取卡片当前状态
            $cardData = $this->getCardInfo($data['cid']);
            $cardData = obj_to_arr($cardData);
            if(!$cardData)  json_err( -204,['卡片种类信息，']);
            $res =  (new CardModel())->save([
                'state'     =>  $cardData['state'] == 1 ? 0 : 1,
            ],[
                'cid' =>$data['cid']
            ]);
            return $res;
        }
        return false;
    }

    // 根据激活码获取卡片产品信息
    public function s_get_card_info($data){
	    $CardProModel = new CardProModel();
        if(!empty($data['active_code'])){
            $cardProInfo = $CardProModel->where('password',$data['active_code'])->find();
        }else if(!empty($data['pid'])){
            $cardProInfo = $CardProModel->where('pid',$data['pid'])->find();
        }
        $cardProInfo = obj_to_arr($cardProInfo);
        if(!$cardProInfo) json_err(-210,['未找到卡片产品相关信息！']);
        if($cardProInfo && (int)$cardProInfo['state'] !== 1) json_err(-210,['卡片产品被禁用！']);
        // 获取卡片信息
        $CardModel = new CardModel();
        $CardInfo = $CardModel->where('cid',$cardProInfo['cid'])->find();
        $CardInfo =obj_to_arr($CardInfo);
        if(!$CardInfo)  json_err(-210,['未找到卡片相关信息！']);
        if($CardInfo && (int)$CardInfo['state'] !== 1) json_err(-210,['卡片被禁用！']);
        // 获取卡片类型
        $CardTypeService =   new CardTypeService();
        $CardTypeInfo = $CardTypeService->s_card_type_info($CardInfo['ct_id']);
        $CardTypeInfo =obj_to_arr($CardTypeInfo);
        if(!$CardTypeInfo)  json_err(-210,['未找到卡片类型相关信息！']);
        if($CardTypeInfo && (int)$CardTypeInfo['state'] !== 1) json_err(-210,['卡片类型被禁用！']);

        $userCard = (new CardUserModel())->where('pid',$cardProInfo['pid'])->find();
        if($userCard){
            $userCard = obj_to_arr($userCard);
            $cardProInfo['activeTime'] = $userCard['creation_time'];
            $cardProInfo['validTimeBegin'] = $userCard['creation_time'];
            $cardProInfo['validTimeEnd'] = date("Y-m-d H:i:s", $userCard['valid_time']);
        }

        $IdentityCardModel = new IdentityCardModel();
        $IdentityCardInfo = $IdentityCardModel->where('uid',$data['uid'])->find();

        $bind_agent_card_info= (new CardUserService())->s_bind_agent_card_info($cardProInfo['pid'],$data['uid']);
        if($bind_agent_card_info){
            $IdentityCardInfo = $IdentityCardModel->where('did', $bind_agent_card_info['did'])->find();
        }

        $familys = [];
        if($CardTypeInfo['type']==2){
            // 家庭卡
            $familyCardModel = new FamilyCardModel();
            $familys = $familyCardModel->alias('f')
            ->join('identity_card ic', 'ic.did=f.did')
            ->field('f.type,ic.name,ic.birth,ic.id_card,f.state')
            ->where(['f.pid'=>$cardProInfo['pid'],'f.state'=>1])->select();
            if($familys){
                $familys=obj_to_arr($familys);
            }
        }

        return [
            'card_pro'    =>   $cardProInfo,
            'card_info'   =>   $CardInfo,
            'card_type'   =>   $CardTypeInfo,
            'card_family' =>   $familys,
            'user_card'   =>   $userCard,
            'identity_card_info' => $IdentityCardInfo
        ];
    }

    // 根据卡号获取卡片可激活时间范围
    public function s_get_card_active_period($data){
        $CardProModel = new CardProModel();
        $cardProInfo = $CardProModel->where('code',$data['code'])->find();
        $cardProInfo = obj_to_arr($cardProInfo);
        if(!$cardProInfo) json_err(-210,['未找到卡片产品相关信息！']);
        if($cardProInfo && (int)$cardProInfo['state'] !== 1) json_err(-210,['卡片产品被禁用！']);
        // 获取卡片信息
        $CardModel = new CardModel();
        $CardInfo = $CardModel->where('cid',$cardProInfo['cid'])->find();
        $CardInfo =obj_to_arr($CardInfo);
        if(!$CardInfo)  json_err(-210,['未找到卡片相关信息！']);
        if($CardInfo && (int)$CardInfo['state'] !== 1) json_err(-210,['卡片被禁用！']);
        // 获取卡片类型
        $CardTypeService =   new CardTypeService();
        $CardTypeInfo = $CardTypeService->s_card_type_info($CardInfo['ct_id']);
        $CardTypeInfo =obj_to_arr($CardTypeInfo);
        if(!$CardTypeInfo)  json_err(-210,['未找到卡片类型相关信息！']);
        if($CardTypeInfo && (int)$CardTypeInfo['state'] !== 1) json_err(-210,['卡片类型被禁用！']);

        $begin = "";
        if($cardProInfo['outbound']===null){
            $begin = $cardProInfo['creation_time'];
        }else if($cardProInfo['outbound_time']!==null){
            $begin = $cardProInfo['outbound_time'];
        }

        $end = "";
        if($CardInfo['active_validity_days']!==null&&$cardProInfo['outbound_time']!==null){
            $end = date('Y-m-d H:i:s', strtotime('+'.$CardInfo['active_validity_days'].' days', strtotime($cardProInfo['outbound_time'])));
        }
        return [
            'begin' =>  $begin,
            'end'   =>   $end
        ];
    }

}
